package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 根据一段日期统计营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //构建dateList
        List<LocalDate> datelist = createDateList(begin, end);
        //构建turnoverList
        //select sum(amount) from order where order_time >startTime and order_time<lastTime and status = 5
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : datelist) {
            Map<String,Object> map= new HashMap<>();
            LocalDateTime startTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime lastTime = LocalDateTime.of(date, LocalTime.MAX);
            map.put("startTime",startTime);
            map.put("lastTime",lastTime);
            map.put("status", Orders.COMPLETED);
            Double amount = orderMapper.getAmountByMap(map);
            amount = amount == null? 0.0 : amount;
            turnoverList.add(amount);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(datelist, ","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //构建dateList
        List<LocalDate> datelist = createDateList(begin, end);
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : datelist) {
            LocalDateTime startTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String,Object> map = new HashMap<>();
            map.put("endTime",endTime);
            //构建totalUserList
            Integer totalUser = userMapper.countByMap(map);
            map.put("startTime",startTime);
            //构建newUserList
            totalUserList.add(totalUser);
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(datelist,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 订单统计
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin,LocalDate end) {
        List<LocalDate> dateList = createDateList(begin, end);
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        for (LocalDate date : dateList) {
            Map<String,Object> map = new HashMap<>();
            LocalDateTime startTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime lastTime = LocalDateTime.of(date, LocalTime.MAX);
            map.put("startTime",startTime);
            map.put("lastTime",lastTime);
            //查询总订单数,select count(id) from order where order_time < ? and order_time >?
            Integer totalDayCount = orderMapper.countByMap(map);
            totalOrderCount += totalDayCount;
            orderCountList.add(totalDayCount);
            //查询邮箱订单数,select count(id) from order where order_time < ? and order_time >? and status = 5
            map.put("status",Orders.COMPLETED);
            Integer validDayOrderCount = orderMapper.countByMap(map);
            validOrderCount+=validDayOrderCount;
            validOrderCountList.add(validDayOrderCount);
        }
        Double orderCompletionRate = totalOrderCount ==0? 0.0 : validOrderCount.doubleValue()/totalOrderCount;
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 根据时间区间获取销量前十
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime startTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime lastTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesDTOList = orderMapper.getTop10(startTime,lastTime);
        List<String> names = salesDTOList.stream().map(GoodsSalesDTO::getName).toList();
        List<Integer> numbers = salesDTOList.stream().map(GoodsSalesDTO::getNumber).toList();

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names,","))
                .numberList(StringUtils.join(numbers,","))
                .build();
    }

    /**
     * 导出Excel报表
     * @param response
     */
    @Override
    public void exportExcel(HttpServletResponse response) {
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        //查询最近30天的数据，概览数据
        BusinessDataVO vo = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));
        //写入到excel
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("templates/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheetAt(0);
            //第2行
            sheet.getRow(1).getCell(1).setCellValue("时间"+beginDate+"至"+endDate);
            //第5行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(vo.getTurnover());
            row.getCell(4).setCellValue(vo.getOrderCompletionRate());
            row.getCell(6).setCellValue(vo.getNewUsers());
            //第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(vo.getValidOrderCount());
            row.getCell(4).setCellValue(vo.getUnitPrice());
            //查询明细数据，并写入
            for (int i = 0; i < 30; i++) {
                LocalDate beginDay = beginDate.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDay, LocalTime.MIN), LocalDateTime.of(beginDay, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(beginDay.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //文件下载
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //资源关闭
            excel.close();
            out.close();
            in.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 根据开始时间和结束时间获取所有时间
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> createDateList(LocalDate begin, LocalDate end){
        List<LocalDate> datelist = new ArrayList<>();
        while (!begin.equals(end)){
            datelist.add(begin);
            begin = begin.plusDays(1);
        }
        datelist.add(end);
        return datelist;
    }

}
